# -*- coding:utf-8 -*-

from tornado.web import HTTPError,authenticated
from libs.handler import BaseHandler

class User(BaseHandler):
	
	def get(self, uid_or_domain):
		query = "SELECT id,nick_name,domain FROM users WHERE "
		if uid_or_domain.isdigit():
			query+="id=%s"
		else:
			query+="domain=%s"
            
		user = self.db.get(query, uid_or_domain)
        
		if not user:
			raise HTTPError(404)
        
		start_page = self.get_argument("start_page",1)
		start = (start_page-1)*16
		
		items = self.db.query("SELECT id,title,price,pic_height,num_iid,like_count,reply_count FROM items \
		WHERE id in(select item_id FROM likes WHERE user_id=%s) ORDER BY id DESC  LIMIT %s,16",user["id"],start);
		
		count = self.db.get("SELECT COUNT(*) AS num FROM likes WHERE user_id=%s",user["id"])
		self.render("user/index.html", user = user, items = items, count = count["num"])


class AccountsBasic(BaseHandler):
    @authenticated
    def get(self):
        self.render("accounts/basic.html")
    
    @authenticated
    def post(self):
        nick_name = self.get_argument("nick_name",None)
        gender    = self.get_argument("gender", 0)
        cannotfind = self.get_argument("cannotfind", 0)
        
        user = self.get_current_user()
        self.db.execute("UPDATE users SET nick_name = %s,gender=%s,cannotfind=%s WHERE id=%s", nick_name, gender, cannotfind, user["id"])
        
        domain = self.get_argument("domain", None)
        if None != domain and ''== user["domain"]:
            self.db.execute("UPDATE users SET domain=%s WHERE id=%s", domain, user["id"])
        
        self.redirect("/accounts/basic")

handlers = []
handlers = [
    (r"/accounts/basic",AccountsBasic),
    (r"/(\w+)",User),
    (r"/(\d+)",User)
]